var COMMON = (function() {
    return {
    	divide: function(numerator, denominator) {
	  		 if (denominator === 0 || isNaN(denominator)) {
			     return 0;
			 } else {
			     return (numerator / denominator).toFixed(4);
			 }
        },
        multiply: function(a, b) {
	  		return (a*b).toFixed(2);
       },
    	
    	isMobileNo: function(str) {
    		return str.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/);
        },
        isEmail: function(str) {
        	return str.match(/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/);
        },
        doAjaxRequest: function(_url, _data, _successFN, _errorFN, _returnDataType, type) {
        	if (!_returnDataType) {
        		_returnDataType = "json";
        	}
        	if (!type) {
        		type = "post";
        	}
        	$.ajax({
        		url : _url, // 请求的url地址
        		dataType : _returnDataType, // 返回格式为json
        		async : true, // 请求是否异步，默认为异步，这也是ajax重要特性
        		data : _data, // 参数值
        		type : type,
        		beforeSend : function() {
        			// 请求前的处理
        		},
        		success : function(req) {
        			// 成功请求并返回
        			if (_successFN) {
        				_successFN(req);
        			}
        		},
        		error : function() {
        			// 请求出现错误
        			if (_errorFN) {
        				_errorFN();
        			} else {
        				COMMON.error();
        			}
        		},
        		complete : function() {
        			// 请求完成的处理
        			// console.log("doAjaxRequest complete");
        		},
        	});
        },
        doPjaxRequest: function(_url, _selector, _successFN) {
        	$.pjax({
        		url : _url,
        		container : _selector,
        		push : true,
        		replace : false,
        		type : "GET",
        		dataType : "html",
        		timeout : 2500,
        		fragment : _selector
        	}).done(function() {
        		if (_successFN) {
        			_successFN();
        		}
        	});
        },
        loadPage: function(url, selector, _successFN) {
        	COMMON.doPjaxRequest(url, selector, _successFN);
        },
        error: function(msg) {
        	console.log("发生错误");
        	if (msg != null) {
            	toastr["error"](msg);
        	}
        	return;
        },
        success: function(msg) {
        	toastr["success"](msg);
        },
        showLoading: function(msg) {
        	$("body").spin('modal');
        },
        hideLoading: function(msg) {
        	if ($("body").data().spinner) {
        		$("body").spin('modal');
        	}
        },
        initDataTableData: function(datatable, data) {
        	data.startPage = datatable.page.info().page;
            for (var i = 0; i < data.columns.length; i++) {
                column = data.columns[i];
                column.searchRegex = column.search.regex;
                column.searchValue = column.search.value;
                delete(column.search);
            }
        },
        showSideView: function(id, url, data) {
        	if($(".side-view[data-id='" + id + "']").length > 0) {
        		COMMON.closeSideView();
        	} else {
            	if($(".side-view").length > 0) {
            		$(".side-view").attr("data-id", id);
            		$(".side-view-content").html("");
            	} else {
                	$("#main-container").append("<div class='side-view' data-id='" + id + "'><span class='icon-close hand-mouse' onclick='COMMON.closeSideView()'></span><div class='side-view-content'></div></div>");
            	}
            	
        		COMMON.doAjaxRequest(url, data, function(resp){
            		$(".side-view-content").html(resp);
        		}, null, "html");
        		
        	}
        },
        closeSideView: function() {
        	$(".side-view").remove();
        }
    };  
})();

var SCROLL_REFRESH = (function() {
	var scrollObj;
	var isLoading = false;
	var option;
	var startPage = 0;
	var length = 20;
	var handler = function() {
		if (isLoading) {
			return;
		}
		if ($(scrollObj).scrollTop() + $(scrollObj).height() + 30 >= $(scrollObj)[0].scrollHeight) {
			refresh();
		}
	};
	
	var refresh = function(isInit) {
		isLoading = true;
		if(isInit) {
			COMMON.showLoading();
		} else {
			$(option.insertSelector).after('<div class="loader">Loading...</div>');
		}
		var data = {
			startPage: startPage,
			length: length
		};
		data = $.extend(data, option.data);
		COMMON.doAjaxRequest(option.url, data, function(resp) {
			isLoading = false;
			COMMON.hideLoading();
			$(".loader").remove();
			if(resp.respCode != RESP_CODE.SUCCESS) {
				COMMON.error(resp.respMsg);
				SCROLL_REFRESH.destory();
			} else {
				if (option.onComplete) {
					option.onComplete(resp);
				}
				if(isInit) {
		        	$(scrollObj).bind("scroll", handler);
				}
				if(!resp || resp.data.list.length < data.length || resp.data.list.length >= resp.data.total ) {
					SCROLL_REFRESH.destory();
				} else {
					startPage++;
				}
			}
		});
	}
	
    return {
        init: function(_option) {
        	startPage = 0;
        	option = _option;
	    	$(option.insertSelector).html("");
        	scrollObj = $(option.scrollSelector);
        	refresh(true);
        	return this;
        },
	    reload: function() {
        	startPage = 0;
	    	$(option.insertSelector).html("");
	    	refresh(true);
	    },
	    currentPage: function() {
	    	return startPage;
	    },
	    destory: function() {
	    	$(scrollObj).unbind("scroll", handler);
	    }
    };  
})();

var IMAGE_UPLOAD = (function() {
    return {
        init: function(option) {
        	var inputSelector = option.inputSelector;
        	if(inputSelector.length == 0) {
        		return;
        	}
        	var isInitalized = inputSelector.attr("data-init") == "1";
        	if(!isInitalized) {
            	inputSelector.addClass("upload-input");
            	var wrapperClass = option.wrapperClass;
            	if(!wrapperClass) {
            		wrapperClass = "item-add-block-mini";
            	}
            	var name = inputSelector.attr("data-name");
            	var url = inputSelector.attr("data-url");
            	if(url) {
                	inputSelector.wrap('<div class="btn btn-block ' + wrapperClass + '" style="background-image:url(${static.img.url}/' + url + ')"></div>');
            	} else {
                	inputSelector.wrap('<div class="btn btn-block ' + wrapperClass + '"></div>');
            	}
        	}
    		var wrapper = inputSelector.parent();
        	if(!isInitalized) {
            	if(url) {
        			wrapper.append('<span class="icon-close"></span>');
            	}
        		wrapper.append('<input type="hidden" name="' + name + '" value="' + url + '">');
        	}
    		inputSelector.off("click");
        	inputSelector.on('click', function (e) {
        		e.stopPropagation();
            	$(this).fileupload({
            		add: function (e, data) {
            			if (e.isDefaultPrevented()) {
                            return false;
                        }
        				var postData = {
        					"showId": option.showId,
        					"fileTag": option.fileTag,
        					"filename": data.files[0].name
        				};
                		COMMON.showLoading();
                		COMMON.doAjaxRequest("${context.path}/commons/oss/policy.ajax", postData, function(resp){
                			COMMON.hideLoading();
                            if (resp.respCode == RESP_CODE.SUCCESS) {
                				data.url=resp.data.result.host;
                				data.formData=resp.data.result.params;
                                data.process().done(function () {
                                    data.submit();
                                });
                            } else {
                                COMMON.error(resp.respMsg);
                            }
                		});
                    },
            		done: function (e, data) {
            			wrapper.css("background-image", "url('${static.img.url}/" + data.result.picurl + "')");
            			if(wrapper.find(".icon-close").length == 0) {
                			wrapper.append('<span class="icon-close"></span>');
            			}
            			wrapper.find("input[name='" + name + "']").val(data.result.picurl);
            			
            			if(option.callback) {
            				option.callback();
            			}
            		}
            	});
        	});
        	wrapper.off("click", ".icon-close");
        	wrapper.on('click', ".icon-close", function (e) {
        		e.stopPropagation();
        		var obj = $(this);
            	bootbox.confirm({
                    title: '提示',
                    message: '确定删除该图片吗',
          			backdrop: true,
                    callback: function(result) {
                        if (result) {
                			$("input[name='" + name + "']").val("");
                			wrapper.css("background-image", "");
                			obj.remove();
                			
                			if(option.onRemoveCallback) {
                				option.onRemoveCallback();
                			}
                        }
                    }
                });
        	});
        	inputSelector.attr("data-init", "1");
        	return this;
        }
    };  
})();




var TEXT_EDITOR = (function() {
	var editorSelector;
    return {
        init: function(option) {
        	editorSelector = option.editorSelector;
        	var imgFileTag = option.imgFileTag;
        	var showId = option.showId;
        	var content = option.content;
        	editorSelector.summernote({
    		  height: 300,
    		    callbacks: {
    		      onImageUpload: function(files) {
    		      	
    		      }
    		    }
    		});
        	editorSelector.summernote('code', content);
        		
    		$(".note-editor").on('click', ".note-image-input", function(e) {
    			e.stopPropagation();
    			$(this).attr("name", "file");
    	    	$(this).fileupload({
    	    		add: function (e, data) {
    	    			if (e.isDefaultPrevented()) {
    	                    return false;
    	                }
    					var postData = {
    						"showId": showId,
    						"fileTag": imgFileTag,
    						"filename": data.files[0].name
    					};
    	        		COMMON.showLoading();
    	        		COMMON.doAjaxRequest("${context.path}/commons/oss/policy.ajax", postData, function(resp){
    	        			COMMON.hideLoading();
    	                    if (resp.respCode == RESP_CODE.SUCCESS) {
    	        				data.url=resp.data.result.host;
    	        				data.formData=resp.data.result.params;
    	                        data.process().done(function () {
    	                            data.submit();
    	                        });
    	                    } else {
    	                        COMMON.error(resp.respMsg);
    	                    }
    	        		});
    	            },
    	    		done: function (e, data) {
    	    			editorSelector.summernote('insertImage',"${static.img.url}/" + data.result.picurl, 'img');
    	    		}
    	    	});
    		});
        	return this;
        },
        getContent: function() {
        	return editorSelector.summernote('code');
        }
    };  
})();